<template>
  <t-modal
    title="批量移动"
    width="660px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="onSubmit()"
    wrapClassName="move-modal-container"
    forceRender
  >
    <div class="curve-modal-body">
      <div class="move-container">
        <div class="search-warp">
          <a-input-search
            placeholder="请输入关键字"
            style="width: 100%"
            @search="onSearch($event)"
            v-model="keyWord"
            allow-clear
          />
        </div>
        <div class="tree-warp">
          <a-empty v-if="treeData.length == 0" :description="false" />
          <a-tree
            v-else
            show-icon
            show-line
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            :replaceFields="{
              children: 'children',
              title: 'nodeName',
              key: 'uuid',
            }"
            @expand="onExpand"
            @select="onSelect"
          >
            <!-- 自定义图标 -->
            <template slot="custom" slot-scope="{ expanded }">
              <a-icon
                :type="expanded ? 'folder-open' : 'folder'"
                theme="filled"
              />
            </template>
            <template
              slot="title"
              slot-scope="{ nodeName, checkItem, uploadBtn }"
            >
              <div class="custom-tree-title-warp">
                <div class="title" :title="nodeName">
                  {{ nodeName }}
                </div>
                <div class="operate">
                  <a-radio :checked="checkItem" v-if="uploadBtn"> </a-radio>
                </div>
              </div>
            </template>
          </a-tree>
        </div>
      </div>
    </div>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import { addAttributeByKey, flatTreeData, getNodeByKey } from "@/utils/util.js";
import cloneDeep from "lodash.clonedeep";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      keyWord: "",
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      currentTreeNode: {},
    };
  },

  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },

  methods: {
    onSearch() {
      let { keyWord, cloneTreeData } = this;
      let cloneData = cloneDeep(cloneTreeData);
      this.treeData = this.filterTree(cloneData, "children", (node) =>
        node.nodeName.includes(keyWord)
      );
    },
    onSelect(selectedKeys, info) {
      let { uuid, uploadBtn } = info.node.dataRef;
      this.selectedKeys = [uuid];
      if (uploadBtn) {
        this.recursiveTree(this.treeData, uuid);
        this.currentTreeNode = info.node.dataRef;
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //处理节点树
    recursiveTree(data = [], uuid) {
      data.forEach((item) => {
        if (uuid == item.uuid) {
          item.checkItem = true;
        } else {
          item.checkItem = false;
        }
        if (item.children && item.children.length > 0) {
          this.recursiveTree(item.children, uuid);
        }
      });
    },

    getData() {
      let { pageModule } = this.parameter;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/bimCadClassify/getTreeByProCode?type=${pageModule}`,
            {},
            {
              headers: {
                "Content-Type": "application/json;charset=UTF-8",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.cloneTreeData = cloneDeep(data ?? []);
            let flatData = flatTreeData(this.cloneTreeData, "children");
            this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              this.cloneTreeData,
              "children"
            );
            let checkboxData = addAttributeByKey(
              null,
              "checkItem",
              false,
              filterData,
              "children"
            );
            this.treeData = checkboxData ?? [];
            resolve();
          })
          .catch((_) => {
            this.expandedKeys = [];
            this.treeData = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //是否是空对象
    isEmptyObject(obj) {
      return Object.keys(obj).length == 0;
    },

    onSubmit() {
      let { currentTreeNode } = this;
      let { checkRowKeys } = this.parameter;
      let valid = !this.isEmptyObject(currentTreeNode);
      if (valid) {
        return new Promise((resolve, reject) => {
          axios
            .post(
              `/probusiness/bimCadFile/ydFileBatch`,
              {
                classifyId: currentTreeNode.id,
                fileUuid: checkRowKeys,
              },
              {
                headers: {
                  "Content-Type": "application/json;charset=UTF-8",
                },
              }
            )
            .then((res) => {
              let { statusCode } = res;
              if (statusCode == 200) {
                this.$message.success("移动成功！");
                this.closeModal();
                this.$parent.getTableData();
                this.$emit("moveChange");
              } else {
                this.$message.error("移动失败，请稍后重试！");
              }
              resolve();
            })
            .catch((_) => {
              reject();
            });
        });
      } else {
        this.$message.error("请选择目录");
      }
    },

    //关闭弹窗
    closeModal() {
      this.keyWord = "";
      this.expandedKeys = [];
      this.autoExpandParent = true;
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.treeData = [];
      this.currentTreeNode = {};
      this.$emit("update:visible", false);
    },

    //过滤树形数据
    filterTree(data, children = "children", filterFunc) {
      return data
        .filter((node) => {
          // 如果当前节点符合条件，直接返回true
          if (filterFunc(node)) {
            return true;
          }
          // 如果当前节点有子节点，递归过滤子节点
          if (node[children]) {
            node[children] = this.filterTree(
              node[children],
              children,
              filterFunc
            );
            // 如果过滤后的子节点不为空，说明当前节点需要保留
            return node[children].length > 0;
          }
          // 当前节点不符合条件，也没有子节点或子节点不符合条件，返回false
          return false;
        })
        .map((node) => {
          // 创建新对象，避免修改原始数据
          return {
            ...node,
            [children]: node[children]
              ? this.filterTree(node[children], children, filterFunc)
              : [],
          };
        });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.move-modal-container {
  .ant-modal-body {
    padding: 0 !important;
    .curve-modal-body {
      box-sizing: border-box;
      padding: 24px 80px;
      height: 442px;
      overflow: hidden;
      .move-container {
        height: 100%;
        width: 100%;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #d9d9d9;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .search-warp {
          flex-shrink: 0;
          box-sizing: border-box;
          padding: 16px 16px 0 16px;
        }
        .tree-warp {
          flex: 1;
          box-sizing: border-box;
          padding: 16px;
          overflow-y: auto;
          overflow-x: hidden;
          position: relative;
          .ant-tree {
            li {
              width: 100%;
              .ant-tree-node-content-wrapper {
                position: relative;
                width: calc(100% - 25px);
                padding: 0;
                .ant-tree-iconEle {
                  color: #ffca28;
                  font-size: 16px;
                }
                .ant-tree-title {
                  overflow: hidden;
                  display: inline-block;
                  width: calc(100% - 26px);
                  .custom-tree-title-warp {
                    display: flex;
                    width: 100%;
                    .title {
                      flex: 1;
                      overflow: hidden;
                      overflow: hidden;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                    }
                    .operate {
                      flex-shrink: 0;
                    }
                  }
                }
              }
            }
          }
          .ant-empty {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
    }
  }
}
</style>
